class TestP2 {
    private world: p2.World;
    private debugDraw: p2DebugDraw;
    private p2m: number = 30;
    private step: number = 30;

    constructor() {
    }

    private loop(): void {
        this.world.step(1 / this.step);
        if (this.debugDraw != null) {
            this.debugDraw.drawDebug();
        }
    }

    public createWorld(scene: egret.DisplayObjectContainer): void {
        this.world = new p2.World({
            gravity: [0, -10 * this.step / this.p2m],
        });

        (<p2.GSSolver>this.world.solver).iterations = 100;
        (<p2.GSSolver>this.world.solver).tolerance = 0.001;
        scene.addEventListener(egret.Event.ENTER_FRAME, this.loop, this);
    }

    public createDebug(scene: egret.DisplayObjectContainer): void {
        this.debugDraw = new p2DebugDraw(this.world);
        var sprite: egret.Sprite = new egret.Sprite();
        scene.addChild(sprite);
        this.debugDraw.setSprite(sprite);
        this.debugDraw.setP2M(this.p2m);
        this.debugDraw.setLineWidth(0.02);
        sprite.x = 0;
        sprite.y = 0;
        //sprite.scaleX = this.p2m;
        //sprite.scaleY = -this.p2m;

        //this.dragHelper = new DragHelper(this.stage, sprite, this.world);
    }

    public createBox(posX: number, posY: number, w: number, h: number, isStatic: boolean = false) {
        posX = posX / this.p2m;
        posY = -posY / this.p2m;
        w = w / this.p2m;
        h = h / this.p2m;

        var body2 = new p2.Body({
            mass: 1,
            position: [posX, posY],
            angularVelocity: 0,
            type: isStatic ? p2.Body.STATIC : p2.Body.DYNAMIC,
        });
        body2.addShape(new p2.Box({ width: w, height: h }), [0, 0], 0);
        this.world.addBody(body2);
    }
}